package com.aabbc.async.controller;

import com.aabbc.async.task.AsyncTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Instant;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * AsyncController
 *
 * @author: <a href="mailto:chenfenghai@oristartech.com">chenfenghai</a>
 * @version: 1.0
 * @date: 2019-11-28 15:27
 */
@Slf4j
@RestController
public class AsyncController {

    @Autowired
    AsyncTask asyncTask;

    @GetMapping("/test")
    public String test(){
        return "AsyncController.test" + Instant.now().toEpochMilli();
    }

    @GetMapping("/task")
    public String task() throws InterruptedException, ExecutionException {
        long time = System.currentTimeMillis();
        Future<String> task1 = asyncTask.doTask1();
        Future<String> task2 = asyncTask.doTask2();
        while(true) {
            if(task1.isDone() && task2.isDone()) {
                log.info("Task1 result: {}", task1.get());
                log.info("Task2 result: {}", task2.get());
                break;
            }
            log.info("wait for 1s");
            Thread.sleep(1000);
        }
        log.info("耗时:{} ms",System.currentTimeMillis()-time);
        return "success";
    }
}
